"use strict";
const mvc = require("cosjs.mvc");

function arrmap(dataset,fields,format) {
    if(Array.isArray(format) && format.length > dataset.length){
        for(let i = dataset.length;i<format.length;i++){
            dataset.push(format[i])
        }
    }
    else if(!Array.isArray(format) && fields.length > dataset.length){
        for(let i = dataset.length;i<fields.length;i++){
            dataset.push(format)
        }
    }
 
    this.toJSON = function () {
        return dataset;
    }
    this.toString = function () {
        return JSON.stringify(dataset)
    }

    for(let k of fields){
        Object.defineProperty(this, k, {
            set:function(v){
                let i = fields.indexOf(k);
                if(i>=0 && i<dataset.length){
                    dataset[i] = v;
                }
            },
            get:function () {
                let i = fields.indexOf(k);
                return (i>=0 && i<dataset.length)?dataset[i]:null;
            }
        })
    }
}

module.exports = function () {
    return new arrmap(...arguments);
}
//自动使用format中的attach来生成对象
module.exports.attach = function (name,value) {
    let format = mvc.format(name);
    if(!format){
        console.log("arrmap.attach","format not exist",name)
        return false;
    }
    let attach = format["attach"];
    if(!attach['fmt']){
        console.log("arrmap.attach","format fmt empty",name)
        return false
    }
    return new arrmap(value,attach["fmt"],attach["val"]);
}

/* DEMO

let arr = [];
//初始化方法1
let key = ["a","b","c","d","e"];
let def = [1,2,3,4,5];
//初始化方法2
// let key = ["a","b","c","d","e"];
// let def = 0;
//创建对象
let tar = new arrmap(arr,key,def)
console.log("b:",tar.b)
tar.c ++
console.log("c:",tar.c)
console.log(tar.toJSON())

*/